// pages/invoice/new-invoice/new-invoice.js
var httpUtil = require('../../../utils/httpUtil.js');
var uiUtil = require('../../../utils/uiUtil.js');
const app = getApp();
var that;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    invoiceValue:{
      id:null,
      billType: "2",
      companyName: null,
      tfn: null,
      companyAddress: null
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that=this;
    
    if (options.item){
      let item = JSON.parse(options.item);
      that.setData({
        "invoiceValue.id":item.id,
        "invoiceValue.billType": item.billType,
        "invoiceValue.companyName":item.companyName,
        "invoiceValue.tfn": item.tfn,
        "invoiceValue.companyAddress":item.companyAddress,
      })
    }
  },

  /**
  * 选择发票类型
  */
  billTypeChange(e) {
    let billType = e.currentTarget.dataset.billtype;
    
    that.setData({
      "invoiceValue.billType":billType
    })
  },

  /**
  * 保存发票信息
  */
  submitForm(res){
    let value = res.detail.value;
    let billType = that.data.invoiceValue.billType;
    if (billType==1) {
      if (value.companyName==""){
        uiUtil.showToast("请填写发票抬头");
      } else if (value.tfn==""){
        uiUtil.showToast("请填写企业税号");
      } else{
        that.invoiceSubmit(value);
      }
    } else {
      that.invoiceSubmit(value);
    }
  },

  /**
  * 判断提交类型
  */
  invoiceSubmit(value){
    let id = that.data.invoiceValue.id;
    if(id){
      that.getSubmitForm(value);
    } else {
      that.getNewSubmitForm(value);
    }
  },

  /**
  * 保存新发票
  */
  getNewSubmitForm(value){
    let billType = that.data.invoiceValue.billType;
    httpUtil.PostRequest("saveBill", {
      billType: billType,
      companyName: value.companyName,
      tfn: value.tfn,
      companyAddress: value.companyAddress
    }, {
        success(res) {
          uiUtil.showToast("保存成功");
          app.lastPage();
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  },

  /**
  * 修改旧发票
  */
  getSubmitForm(value) {
    let id = that.data.invoiceValue.id;
    let billType = that.data.invoiceValue.billType;
    httpUtil.PostRequest("updateBill", {
      id:id,
      billType: billType,
      companyName: value.companyName,
      tfn: value.tfn,
      companyAddress: value.companyAddress
    }, {
        success(res) {
          uiUtil.showToast("保存成功");
          app.lastPage();
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  }
})